/*
 *  log.c
 *
 *  $Id: log.c 7 2009-08-16 13:27:17Z nramsbottom $	
 *
 */

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "log.h"

static FILE* log_fd;
static char* log_filename;
static char	dttm[15];		// static buffer for date time stamps

int log_open(const char* filename) {
	
	// ensure that any previous log file handles are closed
	log_close();
	
	// open the log for append access
	log_fd = fopen(filename, "a");
	
	// copy the filename into an internal buffer, should it be needed.
	log_filename = (char*)malloc(strlen(filename));
	strcpy(log_filename, filename); 
	
	return log_fd ? 1 : 0;
} //

// cleanup internal variables, close file
int log_close(void) {
	if (log_filename)
		free(log_filename);
	if (log_fd) {
		fflush(log_fd);
		fclose(log_fd);
	}
	log_fd = NULL;
	log_filename = NULL;
	return 1;
}

int log_write(const char* fmt, ...) {
	
	// is the log file open?
	if (log_fd) {
	
		// get the current datetime
		char* timestamp = log_getdttm();
		
		// write log message in format: [yyyymmddHHMMss] <message>
		va_list args;
		va_start(args, fmt);
		fprintf(log_fd, "[%s] ", timestamp);
		vfprintf(log_fd, fmt, args);
		va_end(args);
		fflush(log_fd);
		return 1;
	}
	return 0;
} //


// update datetime buffer with current date and time
// and returns a pointer to the buffer
static char* log_getdttm(void) {
	
	time_t now;
	struct tm* local;
	
	time(&now);
	local = localtime(&now);
	
	strftime(dttm, 15, "%Y%m%d%H%M%s", local);
	
	return dttm;
} //
